<template>
    <el-card>
        <el-button type="primary" @click="dialogVisible = true">新建</el-button>

        <template #header>
            <div>
                商品管理
            </div>
        </template>
        <el-table :data="goodsData">
            <el-table-column label="ID" prop="id">
            </el-table-column>
            <el-table-column label="商品名" prop="goods_name">
            </el-table-column>
            <el-table-column label="缩略图" prop="thumb">
                <template #default="{ row }">
                    <img :src="api.baseURl + row.thumb" alt="" width="300" height="150">
                </template>
            </el-table-column>
            <el-table-column label="描述" prop="des">
            </el-table-column>
            <el-table-column label="原价" prop="sell_price">
            </el-table-column>
            <el-table-column label="售价" prop="show_price">
            </el-table-column>
            <el-table-column label="标签" prop="label">
            </el-table-column>
            <el-table-column label="多个图片" prop="banner">
            </el-table-column>
            <el-table-column label="限量" prop="limi">
            </el-table-column>
            <el-table-column label="编号" prop="number">
            </el-table-column>
            <el-table-column label="成本" prop="cost">
            </el-table-column>
            <el-table-column label="状态" prop="state">
            </el-table-column>
            <el-table-column label="库存" prop="store">
            </el-table-column>
            <el-table-column label="所属分类" prop="subcategory">
            </el-table-column>
            <el-table-column label="是否伪删除" prop="is_delete">
            </el-table-column>



            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="warning" @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="height:60px;" align="middle" justify="center">
            <el-pagination background layout="prev, pager, next" :total="total" v-model:page-size="pageSize"
                v-model:current-page="page" @current-change="getdata" />
        </el-row>
        <!-- 弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增" width="500">
            <el-form label-width="80px" :model="addForm" :rules="rules" ref="formIns">

                <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="缩略图" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.thumb" :src="api.baseURl + addForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="描述" prop="des">
                    <el-input v-model="addForm.des"></el-input>
                </el-form-item>
                <el-form-item label="原价" prop="sell_price">
                    <el-input v-model="addForm.sell_price"></el-input>
                </el-form-item>
                <el-form-item label="售价" prop="show_price">
                    <el-input v-model="addForm.show_price"></el-input>
                </el-form-item>
                <el-form-item label="标签" prop="label">
                    <el-input v-model="addForm.label"></el-input>
                </el-form-item>
                <el-form-item label="图片文件" prop="banner">
                    <el-upload v-model:file-list="fileList" class="upload-demo" :action="api.UPLOAD"
                        :on-success="handleAvatarSuccess3" :on-preview="handlePreview" :on-remove="handleRemove"
                        list-type="picture">
                        <el-button type="primary">Click to upload</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                jpg/png files with a size less than 500kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="限量" prop="limi">
                    <el-input v-model="addForm.limi"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="number">
                    <el-input v-model="addForm.number"></el-input>
                </el-form-item>
                <el-form-item label="成本" prop="cost">
                    <el-input v-model="addForm.cost"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-input v-model="addForm.state"></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="store">
                    <el-input v-model="addForm.store"></el-input>
                </el-form-item>
                <el-form-item label="所属分类" prop="subcategory">
                    <el-input v-model="addForm.subcategory"></el-input>
                </el-form-item>
                <el-form-item label="是否伪删除" prop="is_delete">
                    <el-input v-model="addForm.is_delete"></el-input>
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlesubmit">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog v-model="dialogVisible2" title="编辑" width="500">
            <el-form label-width="80px" :model="editForm" :rules="rules" ref="formIns2">
                <el-form-item label="分类名称" prop="category_name">
                    <el-input v-model="editForm.category_name"></el-input>
                </el-form-item>
                <el-form-item label="图片" prop="thumb">
                    <el-upload class="avatar-uploader" :action="api.UPLOAD" :show-file-list="false"
                        :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload2">
                        <img v-if="editForm.thumb" :src="api.baseURl + editForm.thumb" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                        <template #tip>
                            <div class="el-upload__tip">
                                请上传jpg/png图片,并且小于200kb
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分类级别" prop="pid">
                    <el-input v-model="editForm.pid"></el-input>
                </el-form-item>
                <el-form-item label="排序顺序" prop="sort">
                    <el-input v-model="editForm.sort"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit2">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>
<script setup lang="ts">
// 弹框

const open = () => {
    ElMessageBox.alert('This is a message', 'Title', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: 'OK',
        callback: (action: Action) => {
            ElMessage({
                type: 'info',
                message: `action: ${action}`,
            })
        },
    })
}
import { ref, reactive, onMounted } from 'vue';
import { getGoods, addGoods, delGoods, edtGoods } from '@/api/api';

import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import { ElementPlus } from '@element-plus/icons-vue';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import api from "../api/url"
const iconData = Object.keys(ElementPlusIconsVue)
// 多文件图片相关

import type { FormInstance, FormRules, UploadProps, UploadUserFile, UploadFile, UploadFiles } from "element-plus";
const fileList = ref<UploadUserFile[]>([


])

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (file) => {
    console.log(file)
}

// 查看
const goodsData = ref<GoodsData[]>([]);
onMounted(() => {
    getdata();
})
const pageSize = ref(5);
const total = ref(0);
const page = ref(1);
const getdata = async () => {
    const res = await getGoods({
        page: page.value,
        limit: pageSize.value
    });
    goodsData.value = res.data.data;
    total.value = res.data.total
    console.log(goodsData);

}
// 编辑弹框缩略图触发事件开始
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    addForm.thumb = response.url;

}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type != 'image/png') {
        ElMessage.error('图片格式必须为jpg或者png!')
        return false
    } else if (rawFile.size / 1024 > 200) {
        ElMessage.error('图片大小不能超过200k!')
        return false
    }
    return true
}
// 编辑弹框缩略图触发事件结束
// 编辑弹框图片文件触发事件开始
// const handleAvatarSuccess2: UploadProps['onSuccess'] = (
//     response,
//     uploadFile
// ) => {
//     console.log(response);
//     addForm.banner = response.url;

// }
// const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
//     if (rawFile.type !== 'image/jpeg' && rawFile.type != 'image/png') {
//         ElMessage.error('图片格式必须为jpg或者png!')
//         return false
//     } else if (rawFile.size / 1024 > 200) {
//         ElMessage.error('图片大小不能超过200k!')
//         return false
//     }
//     return true
// }
// 编辑弹框图片文件触发事件
// 图片文件触发事件开始
const handleAvatarSuccess3 = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    let str = "";
    uploadFiles.forEach(v => {
        str += `${v.name}:${(v.response as uploadRes).url};`;
    })
    addForm.banner = str;
}
// 图片文件触发事件结束
// 新增数据
const addForm = reactive<GoodsData>({
    goods_name: "",
    thumb: "",
    des: "",
    sell_price: 0,
    show_price: 0,
    label: "",
    banner: "",
    limi: 0,
    number: "",
    cost: 0,
    state: "",
    store: "",
    subcategory:"",
    update_time: "",
    create_time:"",
    is_delete: "",

});
const rules: FormRules = {
    label: { required: true, message: "请输入label", trigger: "blur" },
    icon: { required: true, message: "请输入icon", trigger: "blur" },
    path: { required: true, message: "请输入path", trigger: "blur" }
}
const dialogVisible = ref(false)
const formIns = ref<FormInstance>();
const handlesubmit = async () => {
    formIns.value?.validate(async (valid) => {
        if (valid) {
            const date=new Date();
            const date2=new Date();
            addForm.create_time=date.toLocaleString();
            addForm.update_time=date2.toLocaleString();
            const res = await addGoods(addForm)
            if (res.data.code === 200) {
                ElMessage.success("修改成功");
                dialogVisible.value = false;
                formIns.value?.resetFields();
                getdata();
            } else {
                ElMessage.error("修改失败")
            }
        }
    })
}
// 删除
const handleDelete = async (id: number) => {
    try {
        await ElMessageBox.confirm(
            '确认删除当前角色吗',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        const res = await delGoods(id);
        if (res.data.code === 200) {
            ElMessage.success("删除成功");
            getdata();
        } else {
            ElMessage.error("删除失败");
        }
    } catch (e) {
        ElMessage.info("取消删除")
    }
}
//编辑
// const handleChange = async (val: number, id: number) => {
//     const res = await edtGoods(id, { state: val });
//     if (res.data.code === 200) {
//         ElMessage.success("修改成功");
//     }
// }

const dialogVisible2 = ref(false);
const editForm = ref<GoodsData>({
    goods_name: "",
    thumb: "",
    des: "",
    sell_price: 0,
    show_price: 0,
    label: "",
    banner: "",
    limi: 0,
    number: "",
    cost: 0,
    state: "",
    store: "",
    subcategory:"",
    update_time: "",
    is_delete: "",
});
const formIns2 = ref<FormInstance>();
let eidtid = 0;
const handleEdit = (body: GoodsData) => {
    dialogVisible2.value = true;
    editForm.value = body;
    eidtid = body.id as number;
}
const handleSubmit2 = () => {
    formIns2.value?.validate(async valid => {
        if (valid) {
            const res = await edtGoods(eidtid, editForm.value)
            if (res.data.code === 200) {
                dialogVisible2.value = false;
                getdata();
                ElMessage.success("修改成功");
            } else {
                ElMessage.error("删除失败");
            }
        }
    })
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 233px;
    height: 106px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 233px;
    height: 106px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}
</style>